var util = require("../../../libs/util.js");
import * as echarts from '../components/echarts';
var app = getApp();
var chart;
Page({
  onShareAppMessage: function(res) {
    return {
      title: app.appName + '-温度监控',
      path: '/pages/report/pages/tp?shareMode=1&warehouse='
    }
  },
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    ec: {
      lazyLoad: true
    },
    tp_type:'tp1',
    tpData:[]
  },
  onLoad: function(e) {
    var that = this;
    that.setData({
      id: e.id,
      iotbox:e.iotbox
    })
    // 获取组件
    this.ecComponent = this.selectComponent('#tp-chart');

    that.loadData();
  },
  loadData: function () {
    var that = this;
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    util.getData("/atapi/vehicle/vehicle/tp_monitor", {
      id: that.data.id,
      iotbox:that.data.iotbox,
      tp_type: that.data.tp_type
    }, function (res, error) {
      console.log(res);
      console.log(error)
      if (res.data.success) {
        that.setData(res.data.delivery)
        that.setData({
          startTime: res.data.startTime,
          endTime: res.data.endTime,
          tpData:res.data.data,
          tpData2:res.data.data2,
          tpData3:res.data.data3,
          tpData4:res.data.data4,
          maxTp:res.data.maxTp,
          minTp:res.data.minTp,
          shop:res.data.shop
        })
        that.chartInit(res.data.data, res.data.maxTp, res.data.minTp, res.data.startTime, res.data.shop);
      } else {
        wx.showModal({
          title: '温馨提示',
          content: '没有温度监控数据',
          success(res) {
            wx.navigateBack({
              delta: 1
            })
          }
        })
      }
      wx.hideLoading();
    });
  },
  changeTptype:function(e){
    var that = this;
    var tp_type = e.currentTarget.dataset.type
     this.setData({
       tp_type:tp_type
     })
     if(that.data.tpData.length > 0){
       var tpData = that.data.tpData;
       if(tp_type == 'tp2'){
        tpData = that.data.tpData2;
       }
       if(tp_type == 'tp3'){
        tpData = that.data.tpData3;
       }
       if(tp_type == 'tp4'){
        tpData = that.data.tpData4;
       }
       console.log(tpData)
      that.chartInit(tpData, that.data.maxTp, that.data.minTp, that.data.startTime, that.data.shop);
     }else{
        that.loadData();
     }
  },
  onReady() {},
  // 点击按钮后初始化图表
  chartInit: function (data, maxTp, minTp, startTime, shop) {
    this.ecComponent.init((canvas, width, height) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: app.globalData.width,
        height: app.globalData.height - app.globalData.CustomBar - 200
      });

      canvas.setChart(chart);

      setOption(chart, data, this.data.tp_type, maxTp, minTp, startTime, shop, this.data.tp_threshold_max, this.data.tp_threshold_min);

      // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
      this.chart = chart;

      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return chart;
    });
  },
  exportTp:function(){
    var that = this;
    wx.showLoading({
      title: '导出中...',
      mask: true
    })
    util.getData("/atapi/vehicle/vehicle/tp_export", {
      id: that.data.id,
      tp_type: that.data.tp_type
    }, function (res, error) {
      console.log(res);
      console.log(error)
      console.log(res.data)
      wx.hideLoading();
      if (res.data.success) {
        wx.downloadFile({
          url: res.data.data,
          header: 'application/x-excel',
          //filePath: wx.env.USER_DATA_PATH + '11.xls',
          success(res) {
            console.log(res)
            wx.hideLoading();
            const filePath = res.tempFilePath
            wx.openDocument({
              filePath: filePath,
              success: function (res) {
                console.log('打开文档成功')
              }
            })
          }
        });
        console.log(res.data.data)
      }
    });
  }
});

function setOption(chart, data, tp_type, maxTp, minTp, startTime, shop, tp_threshold_max,tp_threshold_min) {
  //每个配送点温度区域
  var markArea = {};
  if(shop && shop.length > 0){
    var markAreaData = [], ma_color = ['#d7f0db', '#d2f1f0', '#cce6ff', '#e1d7f0', '#ede1d9', '#e7ebed', '#fadbd9', '#fde6d2','#fef2ce'];
    for(var i=0;i<shop.length;i++){
      var _ma_color = ma_color[i];
      if (i > ma_color.length){
        _ma_color = ma_color[i / ma_color.length];
      }
      markAreaData.push([{
        name: shop[i].name,
        xAxis: shop[i].start,
        itemStyle: {
          color: _ma_color,
          opacity: 1
        },
        z: 0
      }, {
          xAxis: shop[i].end
      }])
    }
    markArea = {
      data: markAreaData
    }
  }
  //阈值线
  var markLine = {};
  if (maxTp && minTp){
    var markLineData = [{
      yAxis: maxTp,
      lineStyle: {
        color: '#1172cd'
      }
    }, {
      yAxis: minTp,
      lineStyle: {
        color: '#1172cd'
      }
    }];
    if (tp_threshold_max){
      markLineData.push({
        yAxis: tp_threshold_max,
        lineStyle: {
          color: '#ff9700'
        }
      })
    }
    if (tp_threshold_min) {
      markLineData.push({
        yAxis: tp_threshold_min,
        lineStyle: {
          color: '#ff9700'
        }
      })
    }
    markLine = {
      silent: true,
      data: markLineData
    }
  }
  //Y轴数据
  var s_data = data;
  console.log(s_data)
  var series = {
    name: '车厢温度',
    type: 'line',
    itemStyle: { color: 'blue' },
    data: s_data.map(function (item) {
      return item[1];
    }),
    markLine: markLine,
    smooth: true,
    markArea: markArea
  }
  // if(data.length > 0 && data2.length > 0){
  //   series = [{
  //     name: '车厢温度(NT)',
  //     type: 'line',
  //     itemStyle: { color: 'red' },
  //     data: data.map(function (item) {
  //       return item[1];
  //     }),
  //     markLine: markLine,
  //     smooth: true,
  //     markArea: markArea,
  //     z: 2
  //   }, {
  //       name: '车厢温度(TP)',
  //       type: 'line', 
  //       itemStyle:{color:'blue'},
  //       data: data2.map(function (item) {
  //         return item[1];
  //       }),
  //       smooth: true,
  //       z: 3
  //     }]
  // }
  var option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        snap:true,
        animation: true
      },
      position: function (pos, params, dom, rect, size) {
        // 鼠标在左侧时 tooltip 显示到右侧，鼠标在右侧时 tooltip 显示到左侧。
        var obj = { top: 60 };
        obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 5;
        return obj;
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: true,
      data: s_data.map(function (item) {
        return item[0];
      }),
      z:1
    },
    yAxis: {
      type: 'value'
    },
    dataZoom: [{
      show: true,
      startValue: startTime
    }, {
        type: 'inside'
    }],
    visualMap: {
      top: 10,
      right: 10,
      pieces: [{
        gt: 5,
        lte: 10,
        color: '#ff9933'
      }],
      outOfRange: {
        color: '#999'
      }
    },
    series: series
  };
  //console.log(JSON.stringify(option))
  chart.setOption(option);
}